pacman::p_load(tidyverse, corrr, knitr, kableExtra, RColorBrewer)

ead <-  readRDS("Data/Regimedata/Measures_merged.rds")


###Make Tables E2 and E3


df <- ead %>% 
  select(RegType_lied_EA,
                   RegType_RoW_EA,
                   Politytype_Anocracy,
                   status_fh_PF, 
                   HTW_RegType_MP_Autocracy,
                   RegType_magaloni_EA,
                   AnckarRegtype_MP_Autocracy) %>%
  rename(Polity = Politytype_Anocracy, FH = status_fh_PF,
         CPR = AnckarRegtype_MP_Autocracy,
         RoW = RegType_RoW_EA,
         ARD = HTW_RegType_MP_Autocracy,
         LIED = RegType_lied_EA, 
         AoW = RegType_magaloni_EA)


names(df)


a <- df %>%
  filter(LIED == 1 | RoW == 1) %>%
  mutate(agreement = if_else(LIED == RoW, 1, 0)) %>%
  summarize(agreement = mean(agreement, na.rm = T))
a




calculate_agreement_share <- function(data) {
  # Get all combinations of two variables
  variable_combinations <- combn(names(data), 2, simplify = TRUE)
  
  # Check if there are no variable combinations
  if (length(variable_combinations) == 0) {
    stop("There are fewer than two variables in the dataframe.")
  }
  
  # Initialize an empty list to store results
  results_list <- list()
  
  # Iterate over each combination of variables
  for (i in seq_along(variable_combinations[1, , drop = FALSE])) {
    # Extract the current pair of variables
    current_vars <- variable_combinations[, i]
    
    # Step a) Filter observations with at least one variable coded as 1
    subset_data <- data %>%
      filter(across(all_of(current_vars), ~. == 1) %>% rowSums() > 0)
    
    # Check if subset_data is not empty before proceeding
    if (nrow(subset_data) > 0) {
      # Step b) Calculate the share of observations coded as 1 by both variables
      agreement_share <- subset_data %>%
        summarise(share_of_agreement = mean(rowSums(select(., all_of(current_vars))) == length(current_vars)))
      
      # Step c) Store the result in the list
      results_list[[paste(current_vars, collapse = "_")]] <- agreement_share
    }
  }
  
  # Check if there are no results
  if (length(results_list) == 0) {
    stop("There are no valid variable combinations in the dataframe.")
  }
  
  # Combine the results into a tibble
  result_tibble <- bind_rows(results_list, .id = "variable_combination")
  
  return(result_tibble)
}


# Example usage:
# Assuming your dataframe is named 'your_data'
result <- calculate_agreement_share(df)

results <- result %>% 
  separate_wider_delim(variable_combination , 
                       "_", 
                       names = c("Typology_1", "Typology_2"))

results <- rbind(results,
results %>%
  rename(Typology_1 = Typology_2,
         Typology_2 = Typology_1))

results <- results %>% 
  pivot_wider(names_from = "Typology_2", values_from = "share_of_agreement")

# Table E1
results[,c(1,8,2:7)]%>%rename(Typology = Typology_1)



## Democracy

df2 <- ead%>%select(RegType_lied_DEM, RegType_RoW_DEM,  Politytype_Democracy, status_fh_F, HTW_RegType_Democracy, RegType_magaloni_DEM, AnckarRegtype_Democracy)%>%
  rename(Polity = Politytype_Democracy, FH = status_fh_F, CPR = AnckarRegtype_Democracy, RoW = RegType_RoW_DEM, ARD = HTW_RegType_Democracy, LIED = RegType_lied_DEM, AoW = RegType_magaloni_DEM)

result2 <- calculate_agreement_share(df2)

results2 <- result2 %>% 
  separate_wider_delim(variable_combination , 
                       "_", 
                       names = c("Typology_1", "Typology_2"))

results2 <- rbind(results2,
                 results2 %>%
                   rename(Typology_1 = Typology_2,
                          Typology_2 = Typology_1))

results2 <- results2 %>% 
  pivot_wider(names_from = "Typology_2", values_from = "share_of_agreement")


##Table E2
results2[,c(1,8,2:7)]%>%rename(Typology = Typology_1)

